package com.qishon.pc.domain.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipUtils {
	/**
	 * @author yuquan.hu
	 * @描述:压缩包
	 * @param zipFileName
	 *            压缩文件夹c:\\test.zip
	 * @param inputFile
	 *            文件夹c:\\test
	 * @throws Exception
	 */
	public static void zip(String zipFileName, File inputFile,String fileName) throws Exception {
		final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
		zip(out, inputFile, fileName);
		out.close();
	}

	private static void zip(ZipOutputStream out, File f, String base) throws Exception {
		if (f.isDirectory()) {
			String middBase = "";
			final File[] fl = f.listFiles();
			out.putNextEntry(new ZipEntry(base + "/"));
			if (base.length() == 0) {
				middBase = "";
			} else {
				middBase = base + "/";
			}
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], middBase + fl[i].getName());
			}
		} else {
			out.putNextEntry(new ZipEntry(base));
			final FileInputStream in = new FileInputStream(f);
			int b;
			// System.out.println(base);
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
		}
	}
	/**
	 * @author yuquan.hu
	 * @描述:解包
	 * @param basePath
	 *            压缩文件夹c:\\test.zip
	 * @param inputFile
	 *            文件夹c:\\test
	 * @throws Exception
	 */
	public static void unZip(File inputFile,String basePath) throws Exception {
		getZip(inputFile, basePath);
	}
	private static void getZip( File f, String base) throws Exception {
		 ZipInputStream inputStream=new ZipInputStream( new FileInputStream(f));
		 BufferedInputStream Bin=new BufferedInputStream(inputStream);  
         File Fout=null;  
         ZipEntry entry;  
         try {  
             while((entry = inputStream.getNextEntry())!=null){  
            	 if (!entry.isDirectory()) {
                 Fout=new File(base,entry.getName());  
                 if(!Fout.exists()){  
                     (new File(Fout.getParent())).mkdirs();  
                 }  
                 FileOutputStream out=new FileOutputStream(Fout);  
                 BufferedOutputStream Bout=new BufferedOutputStream(out);  
                 int b;  
                 while((b=Bin.read())!=-1){  
                     Bout.write(b);  
                 }  
                 Bout.close();  
                 out.close();  
                 // System.out.println(Fout+"解压成功");  
            	 }
             }  
             Bin.close();  
             inputStream.close();  
         } catch (IOException e) {  
             // TODO Auto-generated catch block  
             e.printStackTrace();  
         }  
	}
}
